#import "RNNewListItemSheetController.h"
#import "RNConstants.h"

#define RNNewListItemSheetCancel 0
#define RNNewListItemSheetCreateNewItem 1
#define RNNewListItemSheetAddItem 2

@implementation RNNewListItemSheetController

-(void)displayNewListItemSheet {
    [NSApp beginSheet:[self window] modalForWindow:[NSApp mainWindow] modalDelegate:self didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:) contextInfo:nil];
}

-(IBAction)createNewItem:(id)sender {
    [NSApp endSheet:[self window] returnCode:RNNewListItemSheetCreateNewItem];
}

-(IBAction)addItem:(id)sender {
    [NSApp endSheet:[self window] returnCode:RNNewListItemSheetAddItem];
}

-(IBAction)cancelAddItem:(id)sender {
    [NSApp endSheet:[self window] returnCode:RNNewListItemSheetCancel];
}

-(void)sheetDidEnd:(NSWindow *)sheet returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo {
    [sheet orderOut:self];
    if (returnCode == RNNewListItemSheetCreateNewItem) 
        [NSApp sendAction:@selector(displayNewItemSheetAndSelectItem:) to:nil from:self];
}

- (NSArray*)control:(NSControl*)control textView:(NSTextView *)textView completions:(NSArray*)words forPartialWordRange:(NSRange)charRange indexOfSelectedItem:(int*)index {
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity:[NSEntityDescription entityForName:@"DatabaseItem" inManagedObjectContext:[self managedObjectContext]]];
    NSString *partialString = [[textView string] substringWithRange:charRange];
    NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"title BEGINSWITH[cd] %@", partialString];
    [fetchRequest setPredicate:filterPredicate];
    NSError *error = nil;
    NSArray *fetchedObjects = [[self managedObjectContext] executeFetchRequest:fetchRequest error:&error];
    if (error)
        [NSApp presentError:error];
    NSMutableArray *strings = [[fetchedObjects valueForKey:RNTitleKey] mutableCopy];
    [strings sortUsingSelector:@selector(compare:)];
    return strings;
}

- (void)controlTextDidChange:(NSNotification*)notification {
	NSTextView* textView = [[notification userInfo] objectForKey:@"NSFieldEditor"];
    
    if (!completePosting && !commandHandling)	// prevent calling "complete" too often
	{
        completePosting = YES;
        [textView complete:nil];
        completePosting = NO;
    }
}

- (BOOL)control:(NSControl*)control textView:(NSTextView*)textView doCommandBySelector:(SEL)commandSelector {
    if (![textView respondsToSelector:commandSelector]) 
        return NO;
    
    commandHandling = YES;
    [textView performSelector:commandSelector withObject:nil];
    commandHandling = NO;
    
    return YES;
}


@end